//
//  EssenceRecommendController.m
//  项目A_百思不得姐
//
//  Created by wudongyang on 16/5/16.
//  Copyright © 2016年 wudongyang. All rights reserved.
//

#import "EssenceRecommendController.h"
#import "PictureTableViewCell.h"
#import <AFNetworking.h>
#import "PictureModel.h"
#import "MJRefresh.h"
#import "CommentsViewController.h"
static NSString *const firstCell = @"firstCell";

@interface EssenceRecommendController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong)UITableView *myTableView;
@property(nonatomic, strong)NSMutableArray *allArray;
@property(nonatomic, strong)NSMutableArray *cacheArray;
@property(nonatomic, assign)BOOL isUpLoading;
@property(nonatomic, assign)NSInteger nextPage;

@end

@implementation EssenceRecommendController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.allArray = [NSMutableArray array];
    
    
    
    // 设置背景色
    self.view.backgroundColor = DSRGBA(223, 223, 223, 1);
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 155) style:UITableViewStylePlain];
    self.myTableView.backgroundColor = [UIColor whiteColor];
    self.myTableView. dataSource = self;
    self.myTableView.delegate = self;
    [self.view addSubview:self.myTableView];
    [self.myTableView registerClass:[PictureTableViewCell class] forCellReuseIdentifier:firstCell];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 程序运行期间就存在的数据库
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:nil forKey:@"userName"];
    [defaults setObject:nil forKey:@"pwd"];
    [defaults setObject:@"0"  forKey:@"isLogin"];
    // 存入网盘
    [defaults synchronize];
    
    self.isUpLoading = NO;
    [self addFooter];
    [self addHeader];
    // 刚进界面就刷新
    [self.myTableView.mj_header beginRefreshing];
}
-(void)read{
    self.cacheArray = [NSMutableArray array];
    // 从document本地取出listArray
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *listArrayPath = [path stringByAppendingPathComponent:@"listArray.txt"];
    NSArray *listArray = [NSArray arrayWithContentsOfFile:listArrayPath];
    if (listArray.count != 0) {
        for (NSDictionary *dic in listArray) {
            PictureModel *model = [[PictureModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.cacheArray addObject:model];
         //   DSLog(@"%@",self.cacheArray);
        }
    }
    [self.myTableView reloadData];
//    [self.myTableView.mj_header endRefreshing];
//    DSLog(@"%ld",self.cacheArray.count);
}
#pragma mark --下拉刷新
-(void)addHeader{
    //block中不能使用self,会报错
    __block EssenceRecommendController *recommendVC = self;
    
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        //记录页码
        //recommendVC.nextPage = 0;
        self.nextPage = 0;
        //标记下拉刷新
        recommendVC.isUpLoading = NO;
        //请求数据
        [recommendVC getData:self.nextPage];
        
    }];

    
    self.myTableView.mj_header = header;
}

#pragma mark -- 上拉加载更多
-(void)addFooter{
    
    __block EssenceRecommendController *recommendVC = self;
    //添加上拉刷新尾部控件
    
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
        //上拉一次自增一次
        //recommendVC.nextPage = 0;
        self.nextPage ++;
        //标记为上拉操作
        recommendVC.isUpLoading = YES;
        //请求数据
        [recommendVC getData:self.nextPage];
        
        
        
        
    }];
    

    self.myTableView.mj_footer = footer;
    
}
-(void)getData:(NSInteger)nextPage{
    //GET请求
    NSString *url = [NSString stringWithFormat:@"http://s.budejie.com/topic/list/jingxuan/1/bs0315-iphone-4.1/%ld-20.json",nextPage * 1464579826];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@",responseObject);
        NSMutableArray *listArray = [responseObject objectForKey:@"list"];
        // 将listArray存到documents本地
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSLog(@"%@",path);
        NSString *listArrayPath = [path stringByAppendingPathComponent:@"listArray.txt"];
        [listArray writeToFile:listArrayPath atomically:YES];
        
        for (NSDictionary *dic in listArray) {
            PictureModel *pictureModel = [[PictureModel alloc] init];
            [pictureModel setValuesForKeysWithDictionary:dic];
            [self.allArray addObject:pictureModel];
        }
        [self.myTableView reloadData];
        //停止刷新
        [self.myTableView.mj_footer endRefreshing];
        [self.myTableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
         [self.myTableView.mj_header endRefreshing];
        [self read];
       
//        DSLog(@"%ld",self.cacheArray.count);
    }];


}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.allArray.count == 0) {
        return self.cacheArray.count;
    }else{
        return self.allArray.count;
    }
}
// cell将要消失的时候走的方法
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(PictureTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.isPlay = NO;
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PictureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:firstCell];
    if (self.allArray.count == 0) {
        PictureModel *model = [self.cacheArray objectAtIndex:indexPath.row];
        DSLog(@"没网走这个");
        cell.pictureModel = model;
        
    }else{
        PictureModel *model = [self.allArray objectAtIndex:indexPath.row];
        cell.pictureModel = model;
        cell.isPlay = NO;

        DSLog(@"有网走这个");
    }
    cell.selectionStyle = 0;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    PictureModel *pictureModel = [[PictureModel alloc]init];
    if (self.allArray.count == 0) {
        pictureModel = [self.cacheArray objectAtIndex:indexPath.row];
    }else{
        pictureModel = [self.allArray objectAtIndex:indexPath.row];
    }
    
  
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17],NSFontAttributeName, nil];
    CGRect rect = [pictureModel.text boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    if ([pictureModel.type isEqualToString:@"gif"]) {
        CGFloat gifHeight = pictureModel.gifModel.height.intValue * 394 / pictureModel.gifModel.width.intValue;
        CGFloat ImageHeight = gifHeight;
        return rect.size.height + ImageHeight + 160;
    }
    if ([pictureModel.type isEqualToString:@"video"]) {
        CGFloat videoHeight = pictureModel.videoModel.height.intValue * 394 / pictureModel.videoModel.width.intValue;
        CGFloat ImageHeight = videoHeight;
        return rect.size.height + ImageHeight + 160;
    }if ([pictureModel.type isEqualToString:@"image"]) {
        CGFloat imageHeight = pictureModel.imageModel.height.intValue * 394 / pictureModel.imageModel.width.intValue;
        
        CGFloat ImageHeight = imageHeight;
        return rect.size.height + ImageHeight + 160;
    }
    return 0;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DSLog(@"Cell点击方法");
    
    if (self.allArray.count == 0) {
        // 给小菊花添加文字
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"网络不给力";
        // 取消小菊花图案
//        hud.mode = MBProgressHUDModeCustomView;
        [hud hide:YES afterDelay:1];
        
    }else{
        
        CommentsViewController *commentsVC = [[CommentsViewController alloc] init];
        PictureModel *model = self.allArray[indexPath.row];
        
       // commentsVC.MineModel.title = model.text;
      //  commentsVC.MineModel.collectId = model.ID;
        commentsVC.myID = model.ID;
        commentsVC.myVideo = model.videoModel.thumbnail.firstObject;
        commentsVC.myGif = model.gifModel.images.firstObject;
        commentsVC.myImage = model.imageModel.big.firstObject;
        commentsVC.myType = model.type;
        commentsVC.myUrl = model.videoModel.video.firstObject;
        commentsVC.myText = model.text;
        DSLog(@"%@",model.text);
        [self.navigationController pushViewController:commentsVC animated:YES];
        
        
        
    }
    
    

}



/*
#pragm  a mark - Navigation

// In a storyboard-based application, you will often want to do-- a 'little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
